var mysql = require('mysql');
var dbConfig = require('./database.config');
var userClass = require("../routes/userClass");


module.exports = {
    query : function(sql, params, callback){
        // You need to create a link each time you use it, and close the connection after the data operation is completed
        let connection = mysql.createConnection(dbConfig);
        connection.connect(function(err){
            if(err){
                console.log('数据库链接失败');
                throw err;
            }
        });
        // Start data operation
        connection.query( sql, params, function(err,results,fields ){
            if(err){
                console.log('数据操作失败');
                throw err;
            }
            // Return the queried data to the callback function
            callback && callback(JSON.parse(JSON.stringify(results)), JSON.parse(JSON.stringify(fields)));
        });
        // results as the result of the data operation, fields as the database connection field
        connection.end(function(err){
            if(err){
                console.log('关闭数据库连接失败！');
                throw err;
            }
        });

    },
    decoding : function (user, field, flagNum) {
        // Decode the string, eliminate the identifier and add the segmented string to the array The identifier is `
        let strBox = "";

        // console.log("field : " + field);

        for (let i = 0; i < field.length; i++){
        // console.log("fieldType : " + typeof (field));
        // console.log("fieldlength : " + field.length);
            let char = field.substring(i, i + 1);

            if (char === '`'){
                switch (flagNum) {
                    case 1: user.taskTitle.push(JSON.parse(JSON.stringify(strBox)));        break;
                    case 2: user.taskContent.push(JSON.parse(JSON.stringify(strBox)));      break;
                    case 3: user.taskPublisher.push(JSON.parse(JSON.stringify(strBox)));    break;
                    case 4: user.taskDate.push(JSON.parse(JSON.stringify(strBox)));         break;
                    default:    break;
                }

                strBox = "";
                continue;
            }

            strBox += char;
        }
    },
    coding : function (field) {
        // To implement data encoding, add an identifier and concatenate the string
        // array into a whole string of characters. The identifier is `
        return field + "`";
    },
};